﻿using cnBlogs.Data;
using cnBlogs.DataModel;
using cnBlogs.Model;
using cnBlogs.ViewModel;
using cnBlogs.Views;
using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using cnBlogs.Common.Helper;
using System.Threading.Tasks;
using System.Linq;

// The Grouped Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234231

namespace cnBlogs
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class MainPage : cnBlogs.Common.LayoutAwarePage
    {
        public MainPage()
        {
            this.InitializeComponent();
            //this.NavigationCacheMode = NavigationCacheMode.Enabled;

        }


        
        MainPageViewModel mainVM;
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
           


            Top48hourArticleViewModel tavm = navigationParameter as Top48hourArticleViewModel;
            if (tavm != null)
            {
                mainVM = tavm;
                await mainVM.ArticleInfoList.LoadMoreItemsAsync(0);
                pageTitle.Text = tavm.Display;
                this.DefaultViewModel["MainVMArticleList"] = mainVM.ArticleInfoList;
                this.DefaultViewModel["QucikNavigation"] = App.DB.ArticleCategoryInfo_Table;
                bt_Category.Visibility = Visibility.Collapsed;
                
            }
            else
            {
                ArticleCategoryInfo categoryinfo = navigationParameter as ArticleCategoryInfo;
                mainVM = categoryinfo == null ? new MainPageViewModel() : new MainPageViewModel(categoryinfo.CategoryLink);
                if (categoryinfo != null && !mainVM.ArticleInfoList.IsBusy)
                {
                    pageTitle.Text = categoryinfo.CategoryName;
                    await mainVM.ArticleInfoList.LoadMoreItemsAsync(0);

                }
                // await mainVM.GetResource();
                // await mainVM.ArticleInfoList.LoadMoreItemsAsync(1);
                // TODO: Create an appropriate data model for your problem domain to replace the sample data
                //var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter);
                //this.DefaultViewModel["Groups"] = sampleDataGroups;

                this.DefaultViewModel["MainVMArticleList"] = mainVM.ArticleInfoList;
                this.DefaultViewModel["QucikNavigation"] = App.DB.ArticleCategoryInfo_Table;

                mainVM.ArticleInfoList.CollectionChanged += ArticleInfoList_CollectionChanged;

            }
        }

        void ArticleInfoList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.NewStartingIndex == 3)
            {
                TileHelper.AddTile(mainVM.ArticleInfoList);
            }


        }



        protected override void SaveState(Dictionary<string, object> pageState)
        {
            base.SaveState(pageState);
            mainVM.ArticleInfoList.CollectionChanged -= ArticleInfoList_CollectionChanged;

        }


        /// <summary>
        /// Invoked when a group header is clicked.
        /// </summary>
        /// <param name="sender">The Button used as a group header for the selected group.</param>
        /// <param name="e">Event data that describes how the click was initiated.</param>
        void Header_Click(object sender, RoutedEventArgs e)
        {
            // Determine what group the Button instance represents
            var group = (sender as FrameworkElement).DataContext;

            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            this.Frame.Navigate(typeof(GroupDetailPage), ((SampleDataGroup)group).UniqueId);
        }

        /// <summary>
        /// Invoked when an item within a group is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var article = ((ArticleInfo)e.ClickedItem);
            this.Frame.Navigate(typeof(ArticleDetail), article);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(ArticleCategory), mainVM.ArticleCategoryViewModel);
        }

        private async void deleted_Click_1(object sender, RoutedEventArgs e)
        {
            Button del = sender as Button;
            ArticleCategoryInfo categoryinfo = del.DataContext as ArticleCategoryInfo;
            App.DB.ArticleCategoryInfo_Table.Remove(categoryinfo);
            await App.DB.SubmitChanges();
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            Storyboard sb;
            if (sp_quickStart.Visibility == Visibility.Visible)
            {
                sb = this.Resources["hideQuidkStartPanel"] as Storyboard;
            }
            else
            {
                sb = this.Resources["showQuickStartPanel"] as Storyboard;
            }
            sb.Begin();
        }

        private void bt_TopView_Click_1(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage), new Top48hourArticleViewModel(TopArticleEnum.Top48Hour));
        }

        private void bt_TopDiggs_Click_1(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage), new Top48hourArticleViewModel(TopArticleEnum.TopTenDay));
        }

        private void lv_quickStart_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            ArticleCategoryInfo category = e.ClickedItem as ArticleCategoryInfo;
            this.Frame.Navigate(typeof(MainPage), category);
        }

        private void bt_News_Click_1(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(NewsView));
        }

    }

   
}
